package com.link.base.base.encode.service;

import com.link.base.base.encode.dao.mybatis.mapper.EncodeMapper;
import com.link.base.base.encode.model.Encode;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;

import java.security.MessageDigest;
/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/12 9:44
 * @version 1.0
 */

public class EncodeServiceImpl implements EncodeService {

    private EncodeMapper encodeMapper;

    private KeyGenerateDao keyGenerateDao;

    @Override
    public void encodeInsert(String attr1, String attr2, String attr3, String attr4, String attr5) throws BasicServiceException {
        Encode encode = new Encode();
        String attr = attr1 + attr2 + attr3 + attr4 + attr5;
        Long randomNum = keyGenerateDao.keyGenerate();
        try {
            String code = md5Encode(attr) + randomNum;
            encode.setId(randomNum);
            encode.setAttr1(attr1);
            encode.setAttr2(attr2);
            encode.setAttr3(attr3);
            encode.setAttr4(attr4);
            encode.setAttr5(attr5);
            encode.setRandomNum(String.valueOf(randomNum));
            encode.setCode(code);
            encodeMapper.insert(encode);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    @Override
    public Encode queryStringByCode(String code) throws BasicServiceException {
        Encode encode = null;
        try {
            encode = encodeMapper.queryStringByCode(code);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return encode;
    }

    @Override
    public void delete(String code) throws BasicServiceException {
        try {
            encodeMapper.delete(code);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    public String md5Encode(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            LCLogger.withException(e);
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
